package com.cpkso.yzx.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.cpkso.yzx.domain.User;
import com.cpkso.yzx.service.InternalService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import runze.util.base.Response;

/**
 * 权限拦截器
 * @author wrzhxy@qq.com
 * @创建时间 2017年3月31日 下午6:33:48
 */
@SuppressWarnings({"serial", "unchecked"})
public class Authority extends MethodFilterInterceptor {
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		// 不被浏览器缓存
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Expires","0");
        // 指定允许其他域名访问  
        response.setHeader("Access-Control-Allow-Origin","*");  
        // 响应类型  
        response.setHeader("Access-Control-Allow-Methods","POST,GET,PUT,DELETE,OPTIONS");  
        // 响应头设置  
        response.setHeader("Access-Control-Allow-Headers", "x-token, Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

		ActionContext context = invocation.getInvocationContext();
		
		// 登录验证
		// 1. 获取请求地址
		String name = context.getName();
 System.out.println("--- url: " + name);		// TODO 获取url 需去掉
 		
 		List<String> urlList = (List<String>) context.getSession().get("urllist");
 		if (urlList == null) {
 			Response requests = internalService.findUrl();
 			urlList = (List<String>) requests.getData();
			context.getSession().put("urllist", urlList);
 		}
 			
// 		if (urlList != null && urlList.indexOf(name) != -1) {
 		if (urlList.indexOf(name) != -1) {
 			// 需要权限判断
 			User user = (User) context.getSession().get("user");
 			if (user == null) return "login";
 			Response judge = internalService.judge(user, name, urlList);
 			if (! judge.getMsg().isSuccess()) return "login";
 		}
 		
		return invocation.invoke();
	}
	
	@Autowired
	private InternalService internalService;
}
